﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace FrogEngine
{
	public class RenderService : GameEntityServiceBase<IRenderable>, IRenderEntityService
	{
		public RenderService(IEngine engine)
			: base(engine)
		{
			this.graphicsDevice = engine.GraphicsDevice;
			this.spriteBatch = engine.SpriteBatch;

			PresentationParameters pp = graphicsDevice.PresentationParameters;
			this.sceneTarget = new RenderTarget2D(graphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat, pp.DepthStencilFormat, 0, RenderTargetUsage.PreserveContents);
			this.sceneRect = new Rectangle(0, 0, pp.BackBufferWidth, pp.BackBufferHeight);

			
		}

		private SpriteBatch spriteBatch;
		private GraphicsDevice graphicsDevice;
		private RenderTarget2D sceneTarget;
		private Rectangle sceneRect;

		
		private BoundingFrustum viewFrustum;

		public RenderTarget2D SceneTarget { get { return this.sceneTarget; } }

		public void Render(GameTime gameTime)
		{
			var cameraService = this.Engine.GetService<CameraService>();
			var camera = cameraService.GetActiveCamera();
			Matrix viewProj = Matrix.Multiply(camera.View, camera.Projection);
			this.viewFrustum = new BoundingFrustum(viewProj);

			graphicsDevice.SetRenderTarget(sceneTarget);
			graphicsDevice.Clear(Color.Black);

			foreach (var entity in this.SubscribedEntities)
			{
				IRenderable renderable = (IRenderable)entity;
				renderable.Render(gameTime);
			}

			graphicsDevice.SetRenderTarget(null);
			spriteBatch.Begin();
			spriteBatch.Draw(sceneTarget, sceneRect, Color.White);
			spriteBatch.End();
		}

		public override void Dispose()
		{
			this.sceneTarget.Dispose();
			base.Dispose();
		}
	}
}
